package com.itchen.hospital.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchen.hospital.exception.CustomException;
import com.itchen.hospital.mapper.AdminMapper;
import com.itchen.hospital.pojo.Admin;
import com.itchen.hospital.pojo.Params;
import com.itchen.hospital.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 查询所有管理员
     * @return
     */
    @Override
    public List<Admin> getAll() {
        return adminMapper.getAll();
    }

    //条件查询
    @Override
    public PageInfo<Admin> search(Params params) {
        //处理分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Admin> list = adminMapper.findBySearch(params);
        return PageInfo.of(list);
    }

    //根据id查询
    @Override
    public Admin findByAdminInfo(String adminInfo) {
        // 使用字符串分割获取 role 属性
        String[] parts = adminInfo.split(", ");
        String role = null;
        for (String part : parts) {
            if (part.startsWith("role=")) {
                role = part.substring(5);
                break;
            }
        }
        Integer adminId = Integer.parseInt(adminInfo.split(", ")[0].split("=")[1]);
        if ("ADMIN".equals(role)){
            return adminMapper.findByAdminInfo(adminId);
        }
        if ("DOCTOR".equals(role)){
            return adminMapper.findByAdminInfo1(adminId);
        }
        if ("USER".equals(role)){
            return adminMapper.findByAdminInfo2(adminId);
        }
        return adminMapper.findByAdminInfo(adminId);
    }

    //添加
    @Override
    public void add(Admin admin) {
        //先查询数据库数据,如果此账号在数据库中已存在，则不能添加
        if (adminMapper.findByAccount(admin.getAccount()) != null) {
            throw new CustomException("此账号已存在,无法添加!");
        }
        admin.setRole("ADMIN");
        //设置默认密码
        admin.setPassword("123456");
        adminMapper.add(admin);
    }

    //修改
    @Override
    public void update(Admin admin) {
        adminMapper.update(admin);
    }

    //根据account查询
    @Override
    public Admin findByAccount(String account) {
        Admin admin = adminMapper.findByAccount(account);
        return admin;
    }

    //删除
    @Override
    public void delete(String account) {
        adminMapper.delete(account);
    }

    //批量删除
    @Override
    public void batchDelete(List<Admin> admins) {
        admins.forEach(admin -> {
            adminMapper.delete(admin.getAccount());
        });
    }
}
